#!/usr/bin/env bash
set -euo pipefail

# 仅启动 FastAPI（不启动 Docker 依赖）

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
LOG_DIR="${ROOT_DIR}/logs"
PID_FILE="${ROOT_DIR}/uvicorn.pid"
LOG_FILE="${LOG_DIR}/uvicorn.log"

cd "${ROOT_DIR}"
mkdir -p "${LOG_DIR}"

command_exists() {
    command -v "$1" >/dev/null 2>&1
}

start_api() {
    if [[ -f "${PID_FILE}" ]] && kill -0 "$(cat "${PID_FILE}")" >/dev/null 2>&1; then
        pid="$(cat "${PID_FILE}")"
        echo "[api] 已在运行 (pid ${pid})"
        return
    fi

    if [[ -x "${ROOT_DIR}/.venv/bin/uvicorn" ]]; then
        UVICORN_BIN="${ROOT_DIR}/.venv/bin/uvicorn"
    elif command_exists uvicorn; then
        UVICORN_BIN="$(command -v uvicorn)"
    else
        echo "[api] ❌ 未找到 uvicorn，请先在虚拟环境中安装依赖"
        exit 1
    fi

    echo "[api] 后台启动 FastAPI 服务 ..."
    nohup "${UVICORN_BIN}" app.main:app --host 0.0.0.0 --port 8080 \
        > "${LOG_FILE}" 2>&1 &
    echo $! > "${PID_FILE}"
    echo "[api] 已启动，PID=$(cat "${PID_FILE}")，日志写入 ${LOG_FILE}"
}

start_api "$@"
